<?php

namespace app\models\common;

use think\Model;
use think\facade\Validate;
use think\facade\Db;

class ModuleModel extends Model
{
    protected $table = 'cm_module';


    /**
     * 记录列表
     * @param array $params
     * @param int $start
     * @param int $size
     * @return array
     */
    public function getRecordList(array $params = [], int $start = 0, int $size = 10)
    {
        $field = [
            'id',
            'code',
            'name',
            'describe'
        ];
        $pdo = self::table($this->table)->field($field);
        $pdo = $this->createSearchParam($pdo, $params);
        if ($size > 0) {
            $pdo->limit($start, $size);
        }
        $list = $pdo->order('id desc')->select();
        $list = $list ? $list->toArray() : [];
        return $list;
    }


    /**
     * 记录数量
     * @param array $params
     * @return mixed
     */
    public function getRecordCount(array $params = [])
    {
        $pdo = self::table($this->table);
        $pdo = $this->createSearchParam($pdo, $params);
        return $pdo->count("*");
    }

    /**
     * 通过id获取详情
     * @param $id
     * @return void
     */
    public function getInfoById($id, array $where = [])
    {
        $field = [
            'id',
            'code',
            'name',
            'describe'
        ];
        $info = self::table($this->table)->field($field)
            ->where(['id' => $id, 'is_delete' => 0])
            ->find();
        $info = $info ? $info->toArray() : [];
        return $info;
    }


    /**
     * 添加
     * @param array $param
     * @return void
     */
    public function createRecord(array $param)
    {
        $checkRes = $this->checkSaveData(0, $param);
        if ($checkRes['status'] != STATUS_CODE_SUCCESS) return $checkRes;
        $data = $checkRes['data'];
        $id = self::insertGetId($data);
        if (!$id) {
            return funReturn(STATUS_CODE_INSIDEERROR, '添加失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, '添加成功', ['id' => $id]);
    }

    /**
     * 修改
     * @param $id
     * @param array $param
     * @return array
     */
    public function updateRecord($id, array $param = [])
    {
        $checkRes = $this->checkSaveData($id, $param);
        if ($checkRes['status'] != STATUS_CODE_SUCCESS) return $checkRes;
        $data = $checkRes['data'];
        $res = self::where(['id' => $id])->update($data);
        if ($res === false) {
            return funReturn(STATUS_CODE_INSIDEERROR, '修改失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, '修改成功');
    }


    /**
     * 删除记录
     * @param $id
     * @return array
     */
    public function deleteRecord($id)
    {
        $res = self::where('id', $id)->update(['is_delete' => Db::raw('id')]);
        if (!$res) {
            return funReturn(STATUS_CODE_INSIDEERROR, '删除失败请重试');
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }


    /**
     * 组装查询条件
     * @param $pdo
     * @param array $param
     * @return mixed
     */
    private function createSearchParam($pdo, array $param = [])
    {
        $pdo->where('is_delete', '=', 0);

        if (isset($param['keywords']) && (string)$param['keywords'] != '') {
            $pdo->where('name|code', 'like', "%{$param['keywords']}%");
        }
        if (isset($param['id']) && intval($param['id']) > 0) {
            $pdo->where('id', '=', $param['id']);
        }
        if (isset($param['ids'][0]) && is_array($param['ids'])) {
            $pdo->whereIn('id', $param['ids']);
        }
        return $pdo;
    }


    /**
     * 校验数据
     * @param $id
     * @param array $params
     * @return array
     */
    private function checkSaveData($id, array $params = [])
    {

        $rule = [
            'name' => 'require|max:30',
            'code' => "require|regex:[0-9a-zA-Z]{4}$|checkCode",
            'describe' => 'max:150',
        ];

        $message = [
            'name.require' => '名称必须',
            'name.max' => '名称最多30个字符',
            'code.require' => '客户端编码必须',
            'code.regex' => '客户端编码格式有误',
            'code.checkCode' => '编码已存在',
            'describe.require' => '说明最多150个字符',
        ];

        $validate = Validate::message($message)->rule($rule);

        $validate->extend('checkCode', function ($value) use ($rule, $params, $id) {
            $map1 = [['code', '=', $value]];
            $map2 = [['id', '<>', $id]];
            $exits = Db::table($this->table)->where([$map1, $map2])->find();
            if ($exits) return false;
            return true;
        });

        if (!$validate->check($params)) {
            return funReturn(STATUS_CODE_DATAERROR, $validate->getError());
        }
        $data = [
            'name' => $params['name'],
            'code' => $params['code'],
        ];
        if (isset($params['describe'])) $data['describe'] = $params['describe'];
        return funReturn(STATUS_CODE_SUCCESS, 'success', $data);

    }

}